桌面版
手機版
然後依照畫面上需要的功能來修改 models,共需要新增五個 models:
package models
// Category defines a category for the app
type Category struct {
BaseModelSoftDelete
Name string `gorm:"not null;unique_index:idx_name"`
Desserts []*Dessert
}
package models
import "github.com/gofrs/uuid"
// Dessert defines a dessert for the app
type Dessert struct {
BaseModelSoftDelete
Name string
Description *string
Unit string
Amount int
AmountMinimum int
AmountInterval int
DegreeTop string
DegreeDown string
BakingTime int // minutes
BigImageURL string
SmallImageURL string
ThumbnailURL string
Steps []*Step
IngredientGroups []*IngredientGroup
CategoryID uuid.UUID
}
package models
import "github.com/gofrs/uuid"
// IngredientGroup defines a ingredientGroup for the app
type IngredientGroup struct {
BaseModelSoftDelete
Name string
Ingredients []*Ingredient
DessertID uuid.UUID
}
package models
import "github.com/gofrs/uuid"
// Ingredient defines a ingredient for the app
type Ingredient struct {
BaseModelSoftDelete
Name string
Unit string
Amount int
IngredientGroupID uuid.UUID
}
package models
import "github.com/gofrs/uuid"
// Step defines a step for the app
type Step struct {
BaseModelSoftDelete
Name string
Content string
Notice string
Order int
DessertID uuid.UUID
}
在改寫的過程發現 schema.graphql 有個地方要小心,用目前的 models 來舉例
錯誤的寫法
type Category {
id: ID!
name: String!
createdAt: Time!
updatedAt: Time
desserts: [Dessert!]
}
正確的寫法
type Category {
id: ID!
name: String!
createdAt: Time!
updatedAt: Time
dessertList: [Dessert!]
}
第一種寫法會讓 gqlgen 沒辦法幫忙生出 Category 的 Desserts resolver,所以往下的查詢就會斷掉,例如我們這樣查詢,就會發現只有 Categories 的 resolver 被觸發,會造成沒辦法拿到下層的資料。
query {
categories {
id
name
dessertList {
id
name
stepList {
name
order
content
notice
}
ingredientGroupList {
name
ingredientList {
name
amount
unit
}
}
}
}
}
完整程式碼 https://github.com/wtlin1228/go-gql-server
有一些東西是需要加到這個專案的,像是 dataloader、permissions、complexity,但由於時間的關係就先擱著,畢竟我的目的是要寫一個 graphql server 來給前端用,接下來我就會以這個後端以及設計稿開始來實作前端囉,第一個框架就選 React 吧。